<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="js/jquery.barrager.js"></script>
    <link rel="stylesheet" href="css/barrager.css">
    <script src="https://cdn.bootcdn.net/ajax/libs/stomp.js/2.3.3/stomp.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/sockjs-client/1.5.1/sockjs.js"></script>
    <style>
        * {
            text-decoration: none;
            list-style: none;
            padding: 0px;
            margin: 0px;
            box-sizing: border-box;
        }

        .video_frame {
            width: 70%;
            height: auto;
            padding: 20px;
        }

        .screen {
            width: 100%;
            height: 100%;
            position: relative;
            overflow: hidden;
            background-color: black;
        }

        .video {
            width: 100%;
            height: 100%;
            max-height: 100vh;
        }

        .comment {
            display: flex;
            width: 100%;
            margin-top: 10px;
        }

        .type_comment {
            width: 100%;
            resize: vertical;
            min-height: 32px;
        }

        .send_barrage {
            width: 50px;
            height: 34px;
            margin-left: 10px;
        }

        @media (max-width: 1440px) {
            .video_frame {
                width: 100%;
            }
        }

        @media (max-width: 768px) {
            .video_frame {
                width: 100%;
                padding: 0px;
            }
        }
    </style>
</head>

<body>
<!-- https://vd4.bdstatic.com/mda-kmd59747apcti6j6/sc/mda-kmd59747apcti6j6.mp4?v_from_s=gz_haokan_4469&auth_key=1624259657-0-0-5158eee5e94f81ce605dc14f35d59434&bcevod_channel=searchbox_feed&pd=1&pt=3&abtest=3000165_1 -->
<!-- https://ks-xpc4.xpccdn.com/25e0278d-9f2c-41fe-9339-f0d903b4a0e8.mp4 -->
<div style="float: right;">
    <span id="to_login"><a href="/login.html" target="_blank">你好，请登录</a></span><br>
    <span id="show_user">用户名<br><a href="/logout">退出登录</a></span>
</div>
<h3 id="audienceNumber">当前有0人在看</h3>
<div class="video_frame">
    <div class="screen" id="screen">
        <video class="video" id="video" loop controls src="">
        </video>
    </div>
    <div class="comment">
        <textarea name="type_comment" class="type_comment" id="type_comment"></textarea>
        <button id="send_barrage" class="send_barrage">发送</button>
    </div>
</div>
<script>
    var socket = new SockJS('http://' + window.location.host + '/video_stomp')
    var stompClient = Stomp.over(socket)
    var video = document.getElementById('video')
    var randomId
    var video_uuid = getQueryVariable('video_uuid')
    var subscribePath
    var sendPath = '/video_destination/barrage'
    var updateTiem = -1
    var connected = false
    var item = {
        img: 'https://dss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=932225914,4019385925&fm=26&gp=0.jpg', //图片
        info: '请填写弹幕文字', //文字
        href: '', //链接
        close: false, //显示关闭按钮
        speed: 10, //延迟,单位秒,默认6
        color: '#ffffff', //颜色,默认白色
        old_ie_color: '#ffffff', //ie低版兼容色,不能与网页背景相同,默认黑色
    }

    isLogin()
    getVideoUrl()
    connect()

    document.getElementById('send_barrage').addEventListener('click', function () {
        let sendValue = document.getElementById('type_comment').value
        let seek = Math.floor(video.currentTime)
        let sendData = 'uuid=' + video_uuid + '&comment=' + sendValue + '&seconds=' + seek
        console.log(sendData)
        fetch('/comment/barrage_comment', {
            method: 'PATCH', headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: sendData
        }).then(resp => {
            resp.text().then(data => {
                console.log(data)
                $('#screen').barrager({
                    img: 'https://dss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=932225914,4019385925&fm=26&gp=0.jpg', //图片
                    info: sendValue, //文字
                    href: '', //链接
                    close: false, //显示关闭按钮
                    speed: 10, //延迟,单位秒,默认6
                    color: 'red', //颜色,默认白色
                    old_ie_color: '#ffffff', //ie低版兼容色,不能与网页背景相同,默认黑色
                })
            })
        }).catch(error => {
            console.log(error)
        })
    })

    function isLogin() {
        fetch('/is_login', {method: 'GET'}).then(resp => {
            resp.json().then(data => {
                if (data.isLogin) {
                    document.getElementById('show_user').textContent = '已登录，用户名：' + data.userName
                    document.getElementById('to_login').style.display = 'none'
                } else {
                    document.getElementById('show_user').style.display = 'none'
                }
            })
        })
    }

    function connect() {
        stompClient.connect({}, function (frame) {
            console.log('连接成功：' + frame)
            connected = true
            fetch('/random_id/' + video_uuid, {}).then(function (res) {
                res.json().then(data => {
                    //console.log(data)
                    randomId = data.randomId
                    subscribePath = '/video_broker/' + randomId + '/' + video_uuid
                    stompClient.subscribe(subscribePath, function (frame2) {
                        let jsonFrame = JSON.parse(frame2.body)
                        document.getElementById('audienceNumber').textContent = '当前有' + jsonFrame.audiences + '人在看'
                        //console.log('jsonFrame：' + jsonFrame)
                        jsonFrame.barrages.forEach(element => {
                            //console.log(element)
                            item.info = element.comment
                            $('#screen').barrager(item)
                        });
                    })
                })
            }).catch(function (err) {
                console.log(err)
                alert('获取客户端randomId失败' + err)
                return
            })
        })
    }

    window.onbeforeunload = function () {
        if (!connected) return

        let msg = {'uuid': video_uuid, 'flag': true}
        stompClient.send(sendPath, {}, JSON.stringify(msg));
    }

    function getVideoUrl() {
        fetch('/get_video_url/' + video_uuid, {method: 'get'}).then(resp => {
            resp.text().then(data => {
                video.setAttribute('src', data)
            })
        }).catch(err => {
            alert('获取视频地址失败：' + err)
        })
    }

    function getQueryVariable(variable) {
        let query = window.location.search.substring(1);
        let vars = query.split("&");
        for (let i = 0; i < vars.length; i++) {
            let pair = vars[i].split("=");
            if (pair[0] == variable) {
                return pair[1];
            }
        }
        return (false);
    }

    setInterval(function () {
        if (!connected) return

        if (!video.paused) {
            let videoCurrentTime = Math.floor(video.currentTime)
            if (videoCurrentTime != updateTiem) {
                updateTiem = videoCurrentTime
                let msg = {'uuid': video_uuid, 'seek': updateTiem, "randomId": randomId, 'flag': false, "playing": true}
                stompClient.send(sendPath, {}, JSON.stringify(msg))
            }
        } else {
            let msg = {'uuid': video_uuid, "randomId": randomId, 'flag': false, "playing": false}
            stompClient.send(sendPath, {}, JSON.stringify(msg))
        }
    }, 1000)
</script>
</body>

</html>